package com.br.framework.excel;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.AbstractView;

import com.br.framework.excel.inter.DataCellStyle;
import com.br.framework.excel.inter.ExcelConvert;
import com.br.framework.excel.inter.HeaderCellStyle;
import com.br.framework.excel.inter.TitleCellStyle;
import com.br.framework.exception.BaseException;
import com.br.framework.util.lang.StringUtil;
import com.br.framework.util.web.ServletUtil;

/**
 * 모델에 있는값을 엑셀로 만든다.
 *
 * */
public class ExcelResolver extends AbstractView{

	public ExcelResolver(){
		setContentType("application/vnd.ms-excel");
	}


	@Override
	protected void renderMergedOutputModel(Map<String, Object> model ,HttpServletRequest requset, HttpServletResponse response) throws Exception {
		Object excelModel = model.get("excelModel");
		HSSFWorkbook wb = null;
		//파일명
		String fileName = "";
		if(excelModel instanceof HSSFWorkbook){
			wb = (HSSFWorkbook)excelModel;
//			파일명설정
			fileName = ExcelUtil.getDownloadFileName(wb);
		}else if(excelModel instanceof ExcelModel){
			ExcelModel devkimExcelModel = (ExcelModel)excelModel;

			//			셀초기 위치를 가지고 온다.
			int titlePosition[] = devkimExcelModel.getTitlePosition();
			int dataPosition[] = devkimExcelModel.getDataPosition();

			String title = devkimExcelModel.getTitle();
			String dataIds[] = devkimExcelModel.getDataId();

			//			데이타 포지션에 대한 validate
			//			데이타 ROW포지션이 제목ROW포지션보다 작거나 같을 경우 제목포지션에 +1값으로 넣는다.
			if(!StringUtil.isEmpty(title)){
				if(dataPosition[0]<=titlePosition[0]){
					dataPosition[0] = titlePosition[0]+1;
				}
			}


			//			DevkimExcelConvert를 가지고 온다.
			ExcelConvert convert = devkimExcelModel.getConvert();
			//			스타일을 가지고 온다.
			TitleCellStyle titleCellStyle = devkimExcelModel.getTitleCellStyle();
			HeaderCellStyle  headerStyle = devkimExcelModel.getHeaderCellStyle();
			DataCellStyle dataCellStyle = devkimExcelModel.getDataCellStyle();
			//			01.sheet를 생성한다.
			wb = ExcelUtil.createWorkbook(devkimExcelModel);
			//			02.타이틀을 생성한다.
			int sheetIdx = 0;
			if(!StringUtil.isEmpty(title)){
				ExcelUtil.createTitle(wb,sheetIdx,titlePosition,title,titleCellStyle);
			}
			@SuppressWarnings("unchecked")
			List<Object> dataList = (List<Object>)devkimExcelModel.getData();
			//			03.헤더를 그린다.
			if(dataList!=null && dataList.size()>0){
				Object obj = dataList.get(0);
				ExcelUtil.createHeader(wb,sheetIdx,dataPosition,dataIds,obj,headerStyle);
			}
			//			04.데이타를 뿌린다.
			ExcelUtil.createDataList(wb,sheetIdx, dataPosition, dataIds, dataList, convert, dataCellStyle);
//			파일명설정
			fileName = ExcelUtil.getDownloadFileName(wb);
		}else{
			Object mvObject = model.get("modelAndView");
			if(mvObject instanceof ModelAndView){
				String excelPath = ((ModelAndView) mvObject).getViewName();
				XLSTransformer transformer = new XLSTransformer();
				String realPath = ServletUtil.getSession().getServletContext().getRealPath(excelPath);
				InputStream is = new FileInputStream(realPath);
				wb = (HSSFWorkbook) transformer.transformXLS(is, ((ModelAndView) mvObject).getModel());
				fileName = StringUtil.substringAfterLast(excelPath,"/");
			}
		}
		if(wb==null){
			throw new  BaseException("common.excel.nodata");
		}
		if(fileName != null){
			fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Content-Transfer-Encoding:", "base64");
			response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ";");
		}
		ByteArrayOutputStream ba = new ByteArrayOutputStream();
		wb.write(ba);
		writeToResponse(response, ba);
	}
}
